//
//  YSProductDetailPropertyView.m
//  Yueshi
//
//  Created by Northwan on 15/7/22.
//  Copyright (c) 2015年 悦食中国. All rights reserved.
//

#import "YSProductDetailPropertyView.h"
#import "YSProductDetailPriceWithSalesView.h"
#import "SpePropertyView.h"
#import "YSProductDetailBusinessIntroduceView.h"
#import "YSClubDataTool.h"
#import "WXClient.h"
#import "CustomShowView.h"
#import "YSShareView.h"
#import "YSBusinessCtrl.h"
#import "YSProductDetailPresentItemView.h"
#import "YSPresent.h"
#import "YSPresentAlertView.h"
#import "YSProdDetailCommentView.h"
#import "MJPhoto.h"
#import "MJPhotoBrowser.h"
#import "YSDeliverTipsView.h"

#define PRODUCT_NAME_FONT 16
#define PRODUCT_DESC_FONT 14
#define OPEN_SKUVIEW_H 43

@interface YSProductDetailPropertyView()<YSProductDetailPresentItemViewDelegate,YSProductDetailBannerViewDelegate>
@property (strong, nonatomic) NSTimer *countDownTimer;
@property (strong, nonatomic) YSProductDetailPriceWithSalesView *pdpsView;
@property (strong, nonatomic) YSDeliverTipsView *deliverTipsView;
@property (strong, nonatomic) SpePropertyView *spePropertyView;
@property (strong, nonatomic) UIView *openSkuView;
@property (strong, nonatomic) UILabel *prodNameLabel;
@property (strong, nonatomic) UILabel *prodDescLabel;
@property (strong, nonatomic) UILabel *prodPromotionLabel;
@property (strong, nonatomic) UILabel *countDownTimeLabel;
@property (strong, nonatomic) UIImageView  *topSpliteView;
@property (strong, nonatomic) UIImageView  *bottomSpliteView;
@property (strong, nonatomic) YSProductDetailPresentItemView *presentItemView;
@property (strong, nonatomic) YSProductDetailBusinessIntroduceView *businessView;
@property (strong, nonatomic) YSProdDetailCommentView *commentView;

@end

@implementation YSProductDetailPropertyView

-(void)bannerItemClick:(NSInteger)tag{
//     self.result.prodImages
    
    NSInteger count =  self.result.prodImages.count;
    // 1.封装图片数据
    NSMutableArray *photos = [NSMutableArray arrayWithCapacity:count];
    for (int i = 0; i<count; i++) {
        MJPhoto *photo = [[MJPhoto alloc] init];
        photo.url = [NSURL URLWithString:self.result.prodImages[i]]; // 图片路径
        
        UIImageView *srcImageView =  [[UIImageView alloc]initWithFrame:self.bannerView.frame];
        [srcImageView setImageURLStr:self.result.prodImages[i]];
        
        photo.srcImageView = srcImageView;//self.photosView[i]; // 来源于哪个UIImageView
        [photos addObject:photo];
    }
    
    // 2.显示相册
    MJPhotoBrowser *browser = [[MJPhotoBrowser alloc] init];
    browser.currentPhotoIndex = tag;//sender.view.tag; // 弹出相册时显示的第一张图片是？
    browser.photos = photos; // 设置所有的图片
    [browser show];
}

-(instancetype)initWithFrame:(CGRect)frame{
    
    self = [super initWithFrame:frame];
    if(self){
        [self setBackgroundColor:[UIColor whiteColor]];
        _bannerView = [[YSProductDetailBannerView alloc]init];
        _bannerView.delegate  = self;
        [self addSubview:_bannerView];
        
        self.pdpsView = [YSProductDetailPriceWithSalesView priceSalesView];
        [self.pdpsView setWidth:SCREENW];
        [self.pdpsView setY:CGRectGetMaxY(self.bannerView.frame)];
        [self addSubview:self.pdpsView];
        
        UILabel *prodNameLabel = [[UILabel alloc]init];
        [prodNameLabel setFont:SYS_FONT(PRODUCT_NAME_FONT)];
        [prodNameLabel setTextColor:HEXColor(@"#333333")];
        [self addSubview:prodNameLabel];
        self.prodNameLabel = prodNameLabel;
        
        UILabel *prodDescLabel = [[UILabel alloc]init];
        [prodDescLabel setFont:SYS_FONT(PRODUCT_DESC_FONT)];
        [prodDescLabel setTextColor:HEXColor(@"#999491")];
        [self addSubview:prodDescLabel];
        self.prodDescLabel = prodDescLabel;
    }
    return self;
}

-(void)timeLabel{
   NSTimeInterval reMainTime = [TimeUtils getRemainTime:_result.prodPromotion.endTime];
    if(reMainTime <= 0){
        [self invalidateTimer];
    }else{
        NSMutableAttributedString *arrstring = [[NSMutableAttributedString alloc]initWithString:@"仅剩"];
        [arrstring appendAttributedString:[self getFormatRemainTime:reMainTime]];
        [self.countDownTimeLabel setAttributedText:arrstring];
    }
}

- (NSMutableAttributedString *)getFormatRemainTime:(long)timeMillis{
    long cutLong = timeMillis / 1000;
    NSMutableString *strin = [NSMutableString string];
    
    int hour = (int) cutLong / (60 * 60);
    int min = (int) (cutLong - hour * 60 * 60) / 60;
    
    NSString *hourFormatStr =  hour > 0 ? [NSString stringWithFormat:@"%d小时",hour]:@"";
    NSString *minFormatStr = min > 0 ? [NSString stringWithFormat:@"%d分",min]:@"1分";
    
    [strin appendString:hourFormatStr];
    [strin appendString:minFormatStr];
    
    NSString *hourStr = [NSString stringWithFormat:@"%d",hour];
    NSString *minStr = [NSString stringWithFormat:@"%d",min];
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:strin];
    [str addAttribute:NSForegroundColorAttributeName value:ThemeColor range:NSMakeRange(0, [hourStr length])];
    [str addAttribute:NSForegroundColorAttributeName value:ThemeColor range:NSMakeRange(hourFormatStr.length,minStr.length)];
    
    return str;
}

-(void)invalidateTimer{
    [_countDownTimer invalidate];
}

-(void)setResult:(YSProductDetailRes *)result{
    _result = result;
    
    //banner
    [_bannerView setBanner:result.prodImages];
    
    //price
    [_pdpsView setResult:result];
    
    CGFloat prodNameY = CGRectGetMaxY(self.pdpsView.frame)+YSPublicXInset;
    //promotion
    if(result.prodPromotion){
        UIImageView *topSpliteView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"bg_promotion"]];
        [topSpliteView setFrame:CGRectMake(YSPublicXInset, CGRectGetMaxY(self.pdpsView.frame), SCREENW-YSPublicXInset*2, 1)];
        [self addSubview:topSpliteView];
        _topSpliteView = topSpliteView;
        
        
        CGFloat bottomSpliteH = 0;
        if(result.prodPromotion.isPanicBuy){//限时抢购
            //限时抢购价
            self.prodPromotionLabel  = [[UILabel alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(topSpliteView.frame)+YSPublicXInset, SCREENW, 16)];
            [self.prodPromotionLabel setTextColor:HEXColor(@"#333333")];
            [self.prodPromotionLabel setFont:SYS_FONT(16)];
            NSString *priceStr = [NSString stringWithFormat:@"¥%.1f",_result.prodPromotion.price];
 
            NSString *formatPriceStr = nil;
            if(result.prodPromotion.whetherShipping){
                formatPriceStr = [NSString stringWithFormat:@"【限时包邮价】%@ ",priceStr];
            }else{
                formatPriceStr = [NSString stringWithFormat:@"【限时抢购价】%@ ",priceStr];
            }
            
            NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:formatPriceStr];
            [str addAttribute:NSForegroundColorAttributeName value:ThemeColor range:NSMakeRange(7,priceStr.length)];
            [self.prodPromotionLabel setAttributedText:str];
            [self addSubview:self.prodPromotionLabel];
            
            //倒计时
            NSMutableAttributedString *arrstring = [[NSMutableAttributedString alloc]initWithString:@"仅剩"];
            [arrstring appendAttributedString:[self getFormatRemainTime:[TimeUtils getRemainTime:result.prodPromotion.endTime]]];
            [self.countDownTimeLabel setAttributedText:arrstring];
            CGSize timeStrSize = [arrstring.string sizeWithFont:SYS_FONT(16)];
            self.countDownTimeLabel  =  [[UILabel alloc] initWithFrame:CGRectMake(SCREENW-timeStrSize.width-YSPublicXInset, CGRectGetMinY(self.prodPromotionLabel.frame), timeStrSize.width, 16)];
            [self.countDownTimeLabel setTextColor:HEXColor(@"#333333")];
            [self.countDownTimeLabel setFont:SYS_FONT(16)];
            [self.countDownTimeLabel setAttributedText:arrstring];
            [self addSubview:self.countDownTimeLabel];
            
            _countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeLabel) userInfo:nil repeats:YES];
            [[NSRunLoop mainRunLoop] addTimer:_countDownTimer forMode:NSDefaultRunLoopMode];
            bottomSpliteH =  CGRectGetMaxY(self.prodPromotionLabel.frame)+YSPublicXInset;
            
        }else if(result.prodPromotion.isPresent){//买赠
            _presentItemView = [YSProductDetailPresentItemView itemView];
            [_presentItemView setWidth:SCREENW];
            [_presentItemView setY:CGRectGetMaxY(topSpliteView.frame)];
            [_presentItemView setX:0];
            [_presentItemView setDelegate:self];
            YSPresent *present =  result.prodPromotion.presentList[0];
            [_presentItemView.presentBtn setTitle:[NSString stringWithFormat:@"【买就赠】%@",present.name] forState:UIControlStateNormal];
            [self addSubview:_presentItemView];
            bottomSpliteH =  CGRectGetMaxY(self.presentItemView.frame);
            
        }
        UIImageView *bottomSpliteView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"bg_promotion"]];
        [bottomSpliteView setFrame:CGRectMake(YSPublicXInset,bottomSpliteH, SCREENW-YSPublicXInset*2, 1)];
        _bottomSpliteView = bottomSpliteView;
        [self addSubview:bottomSpliteView];
        
        prodNameY = CGRectGetMaxY(bottomSpliteView.frame)+YSPublicXInset;
    }
    
    //name
    CGFloat nameInset = 15;
    if (ISBLANK(result.prodName)) {
        nameInset = 0;
    }
    CGSize prodNameSize =  [result.prodName sizeWithFont:SYS_FONT(PRODUCT_NAME_FONT) constrainedToSize:CGSizeMake(SCREENW-YSPublicXInset*2, MAXFLOAT)];
    [self.prodNameLabel setNumberOfLines:0];
    [self.prodNameLabel setFrame:CGRectMake(YSPublicXInset, prodNameY, SCREENW-YSPublicXInset*2, nameInset==0?0:prodNameSize.height)];
    [self.prodNameLabel setText:result.prodName];
    
    //desc
    CGFloat descInset = 15;
    if (ISBLANK(result.prodSellingPoint)) {
        descInset = 0;
    }
    CGSize prodDescSize =[result.prodSellingPoint sizeWithFont:SYS_FONT(PRODUCT_DESC_FONT) constrainedToSize:CGSizeMake(SCREENW-YSPublicXInset*2, MAXFLOAT)];
    [self.prodDescLabel setNumberOfLines:0];
    [self.prodDescLabel setFrame:CGRectMake(YSPublicXInset, CGRectGetMaxY(self.prodNameLabel.frame)+YSPublicXInset, SCREENW-YSPublicXInset*2,  descInset==0?0:prodDescSize.height)];
    [self.prodDescLabel setText:result.prodSellingPoint];
    
    //deliver tips
    self.deliverTipsView = [[YSDeliverTipsView alloc] initWithExplanation:result.explanation];
    [self.deliverTipsView setX:0];
    [self.deliverTipsView setY:CGRectGetMaxY(self.prodDescLabel.frame)+ 15];
    [self addSubview:self.deliverTipsView];
    
    //property
    self.spePropertyView = [[SpePropertyView alloc]initWithArray:result.prodSpeProperty];
    [self.spePropertyView setX:0];
    [self.spePropertyView setY:CGRectGetMaxY(self.deliverTipsView.frame)];
    [self addSubview:self.spePropertyView];
    
    
    CGFloat maxHeight = CGRectGetMaxY(self.spePropertyView.frame)+15;
    
    if(!result.volume&&result.prodSub.count > 1){
        //openSkuView
        UIView *splite1 =  [[UIView alloc]initWithFrame:CGRectMake(YSPublicXInset, CGRectGetMaxY(self.spePropertyView.frame), SCREENW-YSPublicXInset*2, 0.5)];
        [splite1 setBackgroundColor:PUBLIC_BG];
        [self addSubview:splite1];
        self.openSkuView = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(splite1.frame), SCREENW, OPEN_SKUVIEW_H)];
        //title
        UILabel *openSkuViewTitle = [[UILabel alloc]init];
        [openSkuViewTitle setText:@"选择规格"];
        [openSkuViewTitle setFont:SYS_FONT(15)];
        [openSkuViewTitle setTextColor:HEXColor(@"#333333")];
        CGSize titleSize =   [openSkuViewTitle.text sizeWithFont:SYS_FONT(15)];
        [openSkuViewTitle setFrame:CGRectMake(YSPublicXInset, (OPEN_SKUVIEW_H-titleSize.height)/2, titleSize.width, titleSize.height)];
        [self.openSkuView addSubview:openSkuViewTitle];
        //arrow
        UIImage *image = [UIImage imageNamed:@"icon_mine_arrow"];
        UIImageView *rightArrow = [[UIImageView alloc]initWithImage:image];
        [rightArrow setFrame:CGRectMake(self.openSkuView.width-YSPublicXInset*2-image.size.width, (OPEN_SKUVIEW_H-image.size.height)/2, image.size.width, image.size.height)];
        [self.openSkuView addSubview:rightArrow];
        [self addSubview:self.openSkuView];
        
        UITapGestureRecognizer *tapSku = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(openSku:)];
        [self.openSkuView addGestureRecognizer:tapSku];
        maxHeight = CGRectGetMaxY(self.openSkuView.frame);
    }
    
    //商品评论
    if(result.prodComment && result.prodComment.count){
        _commentView = [[YSProdDetailCommentView alloc]initWithComment:result.prodComment];
        [_commentView setX:0];
        [_commentView setY:maxHeight];
        [self addSubview:_commentView];
         maxHeight = CGRectGetMaxY(self.commentView.frame);
    }
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapFrom:)];
    //第三方
    self.businessView = [YSProductDetailBusinessIntroduceView businiessView];
    [self.businessView setX:0];
    [self.businessView setY:maxHeight];
    [self.businessView setSupplier:result.supplier];
    [self.businessView setWidth:SCREENW];
    self.businessView.userInteractionEnabled = YES;
    [self.businessView addGestureRecognizer:tap];
    [self addSubview:self.businessView];
    maxHeight = CGRectGetMaxY(self.businessView.frame);
    
    [self setFrame:CGRectMake(0, 0, SCREENW, maxHeight)];
}

-(void)presentItemClick{
    //买赠点击
    YSPresentAlertView *presentView = [YSPresentAlertView presentAlertView];
    [presentView setInfoWithProdName:_result.prodName prodIcon:_result.prodImages[0]];
    
    CustomShowView *showView = [[CustomShowView alloc]initWithCustomView:presentView location:CustomShowViewLocationCenterType];
    [showView showWithAnim:YES];
}

-(void)tapFrom:(UIGestureRecognizer *)sender{
    // 跳转到商家列表
   YSBusinessCtrl *ctrl =  [[YSBusinessCtrl alloc]initWithSupplierId:_result.supplier.supplierId];
    [self.superview.viewController.navigationController pushViewController:ctrl animated:YES];
}

-(void)tapBack:(UIButton *)sender{
    [self.viewController.navigationController popViewControllerAnimated:YES];
}

-(void)openSku:(UIGestureRecognizer *)sender{
    if ([self.delegate respondsToSelector:@selector(tapOpenSku)]) {
        [self.delegate tapOpenSku];
    }
}

@end
